<template>


    <div>
        <el-row>
            <el-col :span="12">
                <el-button @click="toAdd()">添加</el-button>
            </el-col>
        </el-row>

        <el-table :data="tableData" border style="width: 100%" v-loading="loading">
            <el-table-column prop="roleId" label="roleId" width="180" />
            <el-table-column prop="roleName" label="roleName" width="180" />


            <el-table-column prop="createtime" label="createtime" />
            <el-table-column prop="roleId" label="操作">
                <template #default="scope">
                    <el-button link type="primary" @click="deleteById(scope.row.roleId)">删除</el-button>
                    <el-button link type="primary" @click="toEdit(scope.row.roleId)">修改</el-button>
                </template>
            </el-table-column>

        </el-table>
        <el-pagination v-model:current-page="queryParam.current" :page-sizes="[3, 5, 10, 15, 20, 30, 40]"
            v-model:page-size="queryParam.size" size="default" layout="sizes, prev, pager, next" :total="total"
            @size-change="loadDataList" @current-change="loadDataList" />



        <el-dialog title="角色管理" width="600px" v-model="showEdit">

            <el-form :model="form" label-width="auto">
                <el-form-item label="角色名称">
                    <el-input v-model="form.roleName" />
                </el-form-item>
                <el-form-item label="菜单权限">

                    <el-tree ref="menuTree" node-key="menuId" check-strictly show-checkbox style="max-width: 600px"
                        :data="menuTreeData" :props="defaultProps" />


                </el-form-item>





                <el-form-item>
                    <el-button type="primary" @click="save">保存</el-button>
                    <el-button @click="closeDialog()">Cancel</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>


    </div>




</template>


<script lang="ts" setup name="User">

import { ref, onMounted, reactive, nextTick } from 'vue'
import { service } from "@/utils/request";
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

import { page, list, deleteById as del, queryById, saveOrUpdate, type PageInfo } from '@/utils/crud'

interface Role {
    roleId?: string;
    roleName: string;
    createtime?: string;
    menudIds?: [];
}

interface Meun {

    menuId?: number;
    menuName: string;
    parentId?: number


}


//数据

const tableData = ref<Role[]>()
const queryParam = reactive({
    current: 1,
    size: 10,
});
const total = ref(0);
const loading = ref(false);

const form = reactive<Role>({
    roleName: ''
})
const showEdit = ref(false);


//树的引用对象  
const menuTree = ref(null);





const defaultProps = {
    children: 'children',
    label: 'menuName',
}



const menuTreeData = ref<Meun[]>();
// const menuTreeData = [

//     {
//         menuId: 1,
//         menuName: "系统管理", children: [
//             { menuId: 2, menuName: "用户管理" },
//             { menuId: 3, menuName: "角色管理" },
//             { menuId: 4, menuName: "菜单管理" }

//         ]
//     },
//     {
//         menuId: 6,
//         menuName: "基础信息管理", children: [
//             { menuId: 7, menuName: "部门管理" },
//             { menuId: 8, menuName: "挂号级别管理" },
//             { menuId: 9, menuName: "常数项管理" }
//         ]
//     }


// ]



function loadDataList() {
    loading.value = true;
    // 为给定 ID 的 user 创建请求
    //data  真实的数据
    page<Role>('/role/page', queryParam).then(function (page) {
        tableData.value = page.data;
        total.value = page.total;
        loading.value = false;
    })

}

/**
 * 查询树形菜单列表
 */
function getMenuTree() {
    list<Meun>('/menu/getMenuTree').then(function (data) {
        menuTreeData.value = data;
    })
}




function deleteById(id: string) {
    ElMessageBox.confirm(
        '是否删除数据?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            del('/role/delete', id).then(function (success) {
                if (success) {
                    ElMessage({
                        message: '删除成功',
                        type: 'success'
                    })

                    loadDataList();
                } else {
                    ElMessage({
                        message: '删除失败',
                        type: 'error'
                    })

                }
            })
        })

}

function save() {


    // nextTick(()=>{

    // })

    console.log("menuTree.value", menuTree.value);



    // false 是否只有叶子节点，全部都要 ,  
    // true 包含半选
    if (menuTree.value) {
        let selectMenus = menuTree.value.getCheckedNodes(false, true);
        let menudIds = [];
        selectMenus.forEach(menu => {
            menudIds.push(menu.menuId)
        });


        // console.log("menudIds", menudIds);
        form.menudIds = menudIds;
    }


    saveOrUpdate('/role/saveOrUpdate', form).then(function (success) {
        if (success) {
            ElMessage({
                message: '保存成功',
                type: 'success'
            })
            closeDialog();
            loadDataList();
        } else {
            ElMessage({
                message: '保存失败',
                type: 'error'
            })
        }

    })
}

function toAdd() {
    showEdit.value = true
    delete form.roleId;
    form.roleName = '';
    getMenuTree();
}

function toEdit(id: string) {

    getMenuTree();
    //根据主键查询 数据 放到  form 表单
    queryById<Role>('/role/getById', id).then((vo) => {

        showEdit.value = true;

        form.roleId = vo.roleId;
        form.roleName = vo.roleName;
        console.log("vo.menudIds", vo.menudIds);

        // 
        nextTick(() => {
            if (vo.menudIds) {
                const keys = vo.menudIds.split(",");
                menuTree.value.setCheckedKeys(keys, false)
                console.log("menuTree.value.setCheckedKeys",);
            }
        })


    })

}
function closeDialog() {
    showEdit.value = false
}

onMounted(() => {
    // 获取数据
    loadDataList();
})


</script>